package com.ruoyi.zsyh.controller.applet.machine;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.wx.WXPayConfig;
import com.ruoyi.zsyh.domain.ZsyhPartsQrcodeApply;
import com.ruoyi.zsyh.domain.ZsyhPlatformUser;
import com.ruoyi.zsyh.domain.ZsyhUserRepairstore;
import com.ruoyi.zsyh.service.IZsyhPartsQrcodeApplyService;
import com.ruoyi.zsyh.service.IZsyhPlatformUserService;
import com.ruoyi.zsyh.service.IZsyhUserRepairstoreService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * @author zhangkm
 */
@Controller
@RequestMapping("/applet/zsyh/wxGZHUser/")
public class WxGZHUserController {

    private Logger logger = LoggerFactory.getLogger(WxGZHUserController.class);

    @Value("${wxconfig.appIdWx}")
    private String appIdWx;

    @Value("${wxconfig.appSecretWx}")
    private String appSecretWx;

    @Value("${wxconfig.wxLoginRedirectUri}")
    private String wxLoginRedirectUri;

    @Value("${wxconfig.frontHtmlUrl}")
    private String frontHtmlUrl;


    /**
     * 微信登录——第一步：获取code
     * 注意每个用户只用授权一次，不用重复授权，授权之后就可以获取相关的用户信息
     *
     * @param response
     */
    @RequestMapping(value = "/login")
    public void wechatLogin(HttpServletResponse response, HttpServletRequest request)throws Exception {
        String key = request.getParameter("key");
        String url = wxLoginRedirectUri + "%3fkey%3d" + key;
        String qrconnect = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appIdWx + "&redirect_uri=" + url + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        logger.info("info---------------------------------------------------------qrconnect:" + qrconnect);
        response.sendRedirect(qrconnect);
    }

    /**
     * 微信登录——第二步：通过code换取access_token
     *
     * @param code
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/callback")
    public void wechatCallback(@RequestParam String code, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String key = request.getParameter("key");
        String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appIdWx + "&secret=" + appSecretWx + "&code=" +
                code + "&grant_type=authorization_code";
        logger.info("info---------------------------------------------------------accessTokenUrl:" + accessTokenUrl);
        response.setContentType("text/html;charset=utf-8");
        String json = UrlUtils.loadURL(accessTokenUrl);
        logger.info("info---------------------------------------------------------json:" + json);
        System.out.println("json:" + json);
        Map<String, Object> wechatToken = JSON.parseObject(json, Map.class);
        System.out.println("wechatToken-----------------------------------" + wechatToken);
        System.out.println("openid-----------------------------------" + wechatToken.get("openid").toString());
        System.out.println("access_token-----------------------------------" + wechatToken.get("access_token").toString());
        //验证数据库是否存在该用户

        //返回前端处理
        StringBuilder loginPage = new StringBuilder();
        loginPage.append(frontHtmlUrl + "/machine.html#/authorization");
        loginPage.append("?openId=" + wechatToken.get("openid").toString());
        loginPage.append("&key=" + key);
        logger.info(loginPage.toString());
        response.sendRedirect(loginPage.toString());

    }


}
